package com.mo.sp02.item.controller;

import com.mo.sp01.pojo.Item;
import com.mo.sp01.service.ItemService;
import com.mo.web.util.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Random;

@Slf4j
@RestController
public class ItemContrller {

    @Autowired
    private ItemService itemService;


    @Value("${server.port}")
    private int port;


    //获取商品列表,商品列表封装在JsonResult对象中，在返回给客户端
    //转换的json格式：{"code":200,"msg":"port=8001","data":商品列表数据}
    @GetMapping("/{orderId}")
public JsonResult<List<Item>> getItems(@PathVariable String orderId) throws InterruptedException {

        log.info("获取订单的商品列表.orderId="+orderId);
          // 90%概率，随机延迟
        if(Math.random()<0.9){
     int t=  new Random().nextInt(5000);

            log.info("延迟"+t);
            Thread.sleep(t);

        }




         List<Item> items=itemService.getItems(orderId);
         JsonResult r=JsonResult.ok().msg("port="+port).data(items);
         return  r;
    }



//减少商品库存
    //{code:200,msg:减少商品库存成功，data：null}

    /**
     * @RequestBody 从客户端提交的http协议体body数据中接收json数据
     * @return
     */
    @PostMapping("/decreaseNumber")
    public  JsonResult<?> decreaseNumber(@RequestBody List<Item> items){
               itemService.decreaseNumbers(items);
        return  JsonResult.ok().msg("减少商品库存成功");

    }

}
